package mysql

import (
	"gorm.io/gorm"
	"shopping/logger"
	"shopping/model"
)

// CategoryDao 商品分类Dao
type CategoryDao struct {
	db *gorm.DB
}

// NewCategoryDao 创建NewCategoryDao
func NewCategoryDao(db *gorm.DB) *CategoryDao {
	return &CategoryDao{
		db: db,
	}
}

// Migration 生成商品分类表
func (dao CategoryDao) Migration() {
	err := dao.db.AutoMigrate(&model.Category{})
	if err != nil {
		logger.Log.Info(err.Error())
	}
}

// InsertSampleData 生成商品分类测试数据
func (dao *CategoryDao) InsertSampleData() {
	categories := []model.Category{
		{Name: "CAT1", Desc: "Category 1"},
		{Name: "CAT2", Desc: "Category 2"},
	}
	for _, c := range categories {
		dao.db.Where(model.Category{Name: c.Name}).Attrs(model.Category{Name: c.Name}).FirstOrCreate(&c)
	}
}

// Create 创建商品分类
func (dao *CategoryDao) Create(c *model.Category) error {
	result := dao.db.Create(c)
	if result.Error != nil {
		return result.Error
	}
	return nil
}

// GetByName 通过名称查询商品分类
func (dao *CategoryDao) GetByName(name string) []model.Category {
	var categories []model.Category
	dao.db.Where("name = ?", name).Find(&categories)
	return categories
}

// BulkCreate 批量创建商品分类
func (dao *CategoryDao) BulkCreate(categories []*model.Category) (int, error) {
	var count int64
	err := dao.db.Create(&categories).Count(&count).Error
	return int(count), err
}

// GetAll 获得分页商品分类
func (dao *CategoryDao) GetAll(pageIndex, pageSize int) ([]model.Category, int, error) {
	var categories []model.Category
	var count int64

	err := dao.db.Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&categories).Count(&count).Error
	return categories, int(count), err
}
